package com.choudou5.solr.framework.holder;

import com.choudou5.solr.framework.bean.UserSessionBean;
import com.choudou5.solr.framework.constants.SysConsts;
import com.choudou5.solr.framework.constants.UserConsts;
import com.choudou5.solr.framework.util.cache.CacheHelper;
import com.choudou5.solr.framework.util.cache.EhCacheHelper;
import com.choudou5.solr.util.CookieUtil;
import com.choudou5.solr.util.LogDeBugUtil;
import com.choudou5.solr.util.cache.CacheFactory;
import com.choudou5.solr.util.cache.impl.LRUCache;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;

/**
 * @Name：SessionContextHolder 说明
 * @@author choudou5
 * @@date 2018-07-24
 */
public class SessionContextHolder {

    private static final CacheHelper cacheHelper = EhCacheHelper.getInstance();

    private static final int session_timeout = 30*60*1000;

    private static final LRUCache<String, Map> SESSION_MAP = CacheFactory.newLRUCache(UserConsts.MAX_ONLINE, session_timeout);

    public static void setParam(String name, Object value) {
        String token = RequestContextHolder.getToken();
        if(token == null){
            LogDeBugUtil.debug("setParam token 为空！");
            return;
        }
        String cacheKey = token+":"+name;
        cacheHelper.put(cacheKey, value, session_timeout);
    }

    public static void setParam(String token, String name, Object value) {
        String cacheKey = token+":"+name;
        cacheHelper.put(cacheKey, value, session_timeout);
    }

    public static String getParam(String name) {
        String token = RequestContextHolder.getToken();
        if(token == null){
            LogDeBugUtil.debug(name+" getParam token 为空！");
            return null;
        }
        String cacheKey = token+":"+name;
        return cacheHelper.get(cacheKey);
    }

    public static <T extends Serializable> T getParam(String name, Class<T> classz) {
        String token = RequestContextHolder.getToken();
        if(token == null){
            LogDeBugUtil.debug(name+" getParam token 为空！");
            return null;
        }
        String cacheKey = token+":"+name;
        return cacheHelper.get(cacheKey, classz);
    }


    public static void removeParam(HttpServletRequest request, String name) {
        String token = CookieUtil.getCookie(request, SysConsts.HEADER_TOKEN);
        String cacheKey = token+":"+name;
        cacheHelper.remove(cacheKey);
    }

    public static UserSessionBean getUserSessionBean() {
        return getParam(UserConsts.USER_BEAN_SESSION_KEY, UserSessionBean.class);
    }

    public static void removeUserSessionBean() {
        String cacheKey = RequestContextHolder.getToken()+":"+UserConsts.USER_BEAN_SESSION_KEY;
        LogDeBugUtil.debug("removeUserSessionBean:"+cacheKey);
        cacheHelper.remove(cacheKey);
        cacheHelper.removes();
    }

}
